package job

import (
	"booksmart/book/internal/service"
	logger2 "booksmart/book/pkg/logger"
	"context"
	rlock "github.com/gotomicro/redis-lock"
	"time"
)

type RankingJob struct {
	svc     service.RankingService
	timeout time.Duration
	client  *rlock.Client
	key     string
	l       logger2.LoggerV1
}

func NewRankingJob(svc service.RankingService, timeout time.Duration, client *rlock.Client) *RankingJob {
	return &RankingJob{svc: svc, timeout: timeout, client: client, key: "rlock:corn_job:ranking"}
}

func (r *RankingJob) Name() string {
	return "ranking"
}

func (r *RankingJob) Run() error {
	ctx, cancel := context.WithTimeout(context.Background(), r.timeout)
	defer cancel()
	lock, err := r.client.Lock(ctx, r.key, r.timeout, &rlock.FixIntervalRetry{
		Interval: time.Millisecond * 100,
		Max:      3,
	}, time.Second)
	if err != nil {
		return nil
	}
	defer func() {
		ctx, cancel := context.WithTimeout(context.Background(), time.Second)
		defer cancel()
		errs := lock.Unlock(ctx)
		if errs != nil {
			//释放锁失败，可以重试，也可以不用管，因为有过期时间，大不了等过期时间过了。
			r.l.Error("释放分布式失败 ranking Job", logger2.Error(errs))
		}
	}()
	return r.svc.TopN(ctx)
}
